package com.jeesite.modules.ocr.web;

import java.util.Map;
import java.util.List;

import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.jeesite.common.config.Global;
import com.jeesite.common.collect.ListUtils;
import com.jeesite.common.collect.MapUtils;
import com.jeesite.common.lang.StringUtils;
import com.jeesite.common.idgen.IdGen;
import com.jeesite.modules.sys.utils.UserUtils;
import com.jeesite.common.web.BaseController;
import com.jeesite.modules.ocr.entity.OcrTempateCategory;
import com.jeesite.modules.ocr.service.OcrTempateCategoryService;

/**
 * 模板分类Controller
 * @author 姚海陆,长春叭哥
 * @version 2024-07-28
 */
@Controller
@RequestMapping(value = "${adminPath}/ocr/ocrTempateCategory")
public class OcrTempateCategoryController extends BaseController {

	@Autowired
	private OcrTempateCategoryService ocrTempateCategoryService;
	
	/**
	 * 获取数据
	 */
	@ModelAttribute
	public OcrTempateCategory get(String tempateCategoryCode, boolean isNewRecord) {
		return ocrTempateCategoryService.get(tempateCategoryCode, isNewRecord);
	}

	/**
	 * 管理主页
	 */
	@RequiresPermissions("ocr:ocrTempateCategory:view")
	@RequestMapping(value = "index")
	public String index(OcrTempateCategory ocrTempateCategory, Model model) {
		model.addAttribute("ocrTempateCategory", ocrTempateCategory);
		return "modules/ocr/ocrTempateCategoryIndex";
	}
	
	/**
	 * 查询列表
	 */
	@RequiresPermissions("ocr:ocrTempateCategory:view")
	@RequestMapping(value = {"list", ""})
	public String list(OcrTempateCategory ocrTempateCategory, Model model) {
		model.addAttribute("ocrTempateCategory", ocrTempateCategory);
		return "modules/ocr/ocrTempateCategoryList";
	}
	
	/**
	 * 查询列表数据
	 */
	@RequiresPermissions("ocr:ocrTempateCategory:view")
	@RequestMapping(value = "listData")
	@ResponseBody
	public List<OcrTempateCategory> listData(OcrTempateCategory ocrTempateCategory) {
		if (StringUtils.isBlank(ocrTempateCategory.getParentCode())) {
			ocrTempateCategory.setParentCode(OcrTempateCategory.ROOT_CODE);
		}
		if (StringUtils.isNotBlank(ocrTempateCategory.getTempateCategoryName())){
			ocrTempateCategory.setParentCode(null);
		}
		if (StringUtils.isNotBlank(ocrTempateCategory.getCategoryTagNames())){
			ocrTempateCategory.setParentCode(null);
		}
		if (StringUtils.isNotBlank(ocrTempateCategory.getDescription())){
			ocrTempateCategory.setParentCode(null);
		}
		if (StringUtils.isNotBlank(ocrTempateCategory.getRemarks())){
			ocrTempateCategory.setParentCode(null);
		}
		List<OcrTempateCategory> list = ocrTempateCategoryService.findList(ocrTempateCategory);
		return list;
	}

	/**
	 * 查看编辑表单
	 */
	@RequiresPermissions("ocr:ocrTempateCategory:view")
	@RequestMapping(value = "form")
	public String form(OcrTempateCategory ocrTempateCategory, Model model) {
		// 创建并初始化下一个节点信息
		ocrTempateCategory = createNextNode(ocrTempateCategory);
		model.addAttribute("ocrTempateCategory", ocrTempateCategory);
		return "modules/ocr/ocrTempateCategoryForm";
	}
	
	/**
	 * 创建并初始化下一个节点信息，如：排序号、默认值
	 */
	@RequiresPermissions("ocr:ocrTempateCategory:edit")
	@RequestMapping(value = "createNextNode")
	@ResponseBody
	public OcrTempateCategory createNextNode(OcrTempateCategory ocrTempateCategory) {
		if (StringUtils.isNotBlank(ocrTempateCategory.getParentCode())){
			ocrTempateCategory.setParent(ocrTempateCategoryService.get(ocrTempateCategory.getParentCode()));
		}
		if (ocrTempateCategory.getIsNewRecord()) {
			OcrTempateCategory where = new OcrTempateCategory();
			where.setParentCode(ocrTempateCategory.getParentCode());
			OcrTempateCategory last = ocrTempateCategoryService.getLastByParentCode(where);
			// 获取到下级最后一个节点
			if (last != null){
				ocrTempateCategory.setTreeSort(last.getTreeSort() + 30);
				ocrTempateCategory.setTempateCategoryCode(IdGen.nextCode(last.getTempateCategoryCode()));
			}else if (ocrTempateCategory.getParent() != null){
				ocrTempateCategory.setTempateCategoryCode(ocrTempateCategory.getParent().getTempateCategoryCode() + "001");
			}
		}
		// 以下设置表单默认数据
		if (ocrTempateCategory.getTreeSort() == null){
			ocrTempateCategory.setTreeSort(OcrTempateCategory.DEFAULT_TREE_SORT);
		}
		return ocrTempateCategory;
	}

	/**
	 * 保存数据
	 */
	@RequiresPermissions("ocr:ocrTempateCategory:edit")
	@PostMapping(value = "save")
	@ResponseBody
	public String save(@Validated OcrTempateCategory ocrTempateCategory) {
		
		System.out.println("trainContent:"+ocrTempateCategory.getTrainContent());
		System.out.println("categoryTagNames:"+ocrTempateCategory.getCategoryTagNames());

		ocrTempateCategoryService.save(ocrTempateCategory);
		return renderResult(Global.TRUE, text("保存模板分类成功！"));
	}
	
	/**
	 * 停用数据
	 */
	@RequiresPermissions("ocr:ocrTempateCategory:edit")
	@RequestMapping(value = "disable")
	@ResponseBody
	public String disable(OcrTempateCategory ocrTempateCategory) {
		OcrTempateCategory where = new OcrTempateCategory();
		where.setStatus(OcrTempateCategory.STATUS_NORMAL);
		where.setParentCodes("," + ocrTempateCategory.getId() + ",");
		long count = ocrTempateCategoryService.findCount(where);
		if (count > 0) {
			return renderResult(Global.FALSE, text("该模板分类包含未停用的子模板分类！"));
		}
		ocrTempateCategory.setStatus(OcrTempateCategory.STATUS_DISABLE);
		ocrTempateCategoryService.updateStatus(ocrTempateCategory);
		return renderResult(Global.TRUE, text("停用模板分类成功"));
	}
	
	/**
	 * 启用数据
	 */
	@RequiresPermissions("ocr:ocrTempateCategory:edit")
	@RequestMapping(value = "enable")
	@ResponseBody
	public String enable(OcrTempateCategory ocrTempateCategory) {
		ocrTempateCategory.setStatus(OcrTempateCategory.STATUS_NORMAL);
		ocrTempateCategoryService.updateStatus(ocrTempateCategory);
		return renderResult(Global.TRUE, text("启用模板分类成功"));
	}
	
	/**
	 * 删除数据
	 */
	@RequiresPermissions("ocr:ocrTempateCategory:edit")
	@RequestMapping(value = "delete")
	@ResponseBody
	public String delete(OcrTempateCategory ocrTempateCategory) {
		ocrTempateCategoryService.delete(ocrTempateCategory);
		return renderResult(Global.TRUE, text("删除模板分类成功！"));
	}
	
	/**
	 * 获取树结构数据
	 * @param excludeCode 排除的Code
	 * @param parentCode 设置父级编码返回一级
	 * @param isShowCode 是否显示编码（true or 1：显示在左侧；2：显示在右侧；false or null：不显示）
	 * @return
	 */
	@RequiresPermissions("ocr:ocrTempateCategory:view")
	@RequestMapping(value = "treeData")
	@ResponseBody
	public List<Map<String, Object>> treeData(String excludeCode, String parentCode, String isShowCode) {
		List<Map<String, Object>> mapList = ListUtils.newArrayList();
		OcrTempateCategory where = new OcrTempateCategory();
		where.setStatus(OcrTempateCategory.STATUS_NORMAL);
		if (StringUtils.isNotBlank(parentCode)){
			where.setParentCode(parentCode);
		}
		List<OcrTempateCategory> list = ocrTempateCategoryService.findList(where);
		for (int i=0; i<list.size(); i++){
			OcrTempateCategory e = list.get(i);
			// 过滤非正常的数据
			if (!OcrTempateCategory.STATUS_NORMAL.equals(e.getStatus())){
				continue;
			}
			// 过滤被排除的编码（包括所有子级）
			if (StringUtils.isNotBlank(excludeCode)){
				if (e.getId().equals(excludeCode)){
					continue;
				}
				if (e.getParentCodes().contains("," + excludeCode + ",")){
					continue;
				}
			}
			Map<String, Object> map = MapUtils.newHashMap();
			map.put("id", e.getId());
			map.put("pId", e.getParentCode());
			map.put("name", StringUtils.getTreeNodeName(isShowCode, e.getTempateCategoryCode(), e.getTempateCategoryName()));
			map.put("isParent", !e.getIsTreeLeaf());
			mapList.add(map);
		}
		return mapList;
	}

	/**
	 * 修复表结构相关数据
	 */
	@RequiresPermissions("ocr:ocrTempateCategory:edit")
	@RequestMapping(value = "fixTreeData")
	@ResponseBody
	public String fixTreeData(OcrTempateCategory ocrTempateCategory){
		if (!UserUtils.getUser().isAdmin()){
			return renderResult(Global.FALSE, "操作失败，只有管理员才能进行修复！");
		}
		ocrTempateCategoryService.fixTreeData();
		return renderResult(Global.TRUE, "数据修复成功");
	}
	
}